'use strict';
const Service = require('egg').Service;
const jwt = require('jsonwebtoken');
const { USER_STATUS } = require('../lib/status');

class UserService extends Service {
    async login(username, password) {
        const { app } = this;
        const identify = app.config.identify;
        const user = await app.model.Users.findOne({
            attributes: { exclude: ['password', 'updatedAt', 'createdAt'] },
            where: { username, password },
            raw: true,
        });
        if (!user) {
            return { errcode: app.ERRCODE.DATASET_ERROR, message: '账号或密码有误！' };
        }
        switch (user.status) {
            case USER_STATUS.CANCEL:
                return { errcode: app.ERRCODE.DATASET_ERROR, message: '该用户已作废！' };
            case USER_STATUS.NORMAL:
                return {
                    message: 'success',
                    errcode: app.ERRCODE.NORMAL,
                    data: Object.assign({}, user, {
                        token: jwt.sign({ user_id: user.user_id, username: user.username }, identify.identification, {
                            expiresIn: identify.expiresIn, // 过期时间
                        }),
                    }),
                };
            default:
                return { errcode: app.ERRCODE.DATASET_ERROR, message: '用户状态未知,请联系管理员！' };
        }
    }

    async refreshToken(refreshToken) {
        const { app } = this;
        const identify = app.config.identify;
        const { user_id, username } = jwt.verify(refreshToken, identify.identification, {
            ignoreExpiration: true,
            maxAge: identify.rsExpiresIn,
        });
        const token = jwt.sign({ user_id, username }, identify.identification, { expiresIn: identify.expiresIn });
        return { errcode: app.ERRCODE.NORMAL, message: 'success', token };
    }


    async userList(options = {}) {
        const app = this.app;
        const Op = app.Sequelize.Op;
        const where = {};
        if (options.username) {
            where.username = {
                [Op.like]: `%${options.username}%`,
            };
        }
        if (options.hasOwnProperty('status')) {
            where.status = options.status;
        }
        const userList = await app.model.Users.findAndCountAll({
            attributes: { exclude: ['password', 'updatedAt', 'createdAt'] },
            limit: options.page_size,
            offset: options.page_size * Math.max(0, (options.page - 1)),
            where,
        });
        return { errcode: app.ERRCODE.NORMAL, message: 'success', ...userList };
    }


    async modifyUser(author, options = {}) {
        const { app } = this;
        if (!options.new_password) {
            return { errcode: app.ERRCODE.DATA_ERROR, message: '新密码不能为空' };
        }
        if (author.username !== options.username) {
            return { errcode: app.ERRCODE.DATA_ERROR, message: '用户名输入有误' };
        }
        const user = await this.app.model.Users.findOne({
            where: { user_id: author.user_id },
        });
        if (user.password === options.old_password) {
            user.password = options.new_password;
            await user.save();
            return { errcode: app.ERRCODE.NORMAL, message: '修改成功' };
        }
        return { errcode: app.ERRCODE.DATA_ERROR, message: '旧密码输入有误' };
    }

}

module.exports = UserService;